package cn.qingyun.gis.modules.scenes.service.impl;


import cn.hutool.json.JSONUtil;
import cn.qingyun.gis.exception.CommonException;
import cn.qingyun.gis.modules.init.system.constant.enums.RoleCodeEnum;
import cn.qingyun.gis.modules.init.utils.DateTimeUtil;
import cn.qingyun.gis.modules.scenes.contant.ComConstant;
import cn.qingyun.gis.modules.scenes.entity.AiConversationRecord;
import cn.qingyun.gis.modules.scenes.entity.IntentionEntity;
import cn.qingyun.gis.modules.scenes.entity.IntentionInfo;
import cn.qingyun.gis.modules.scenes.entity.PoiScenarioProofread;
import cn.qingyun.gis.modules.scenes.request.*;
import cn.qingyun.gis.modules.scenes.response.*;
import cn.qingyun.gis.modules.scenes.service.*;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author LHJ
 * @description
 * @date 2024/9/18 11:14
 */
@DS("scenes_offensive")
@Slf4j
@Service
public class IPoiInnerServiceImpl implements IPoiInnerService {

    @Resource
    private IPoiScenarioChannelService iPoiScenarioChannelService;

    @Resource
    private IPoiProofreadService iPoiProofreadService;

    @Resource
    private IPoiScenarioProofreadService poiScenarioProofreadService;

    @Resource
    private IPoiScenarioAppendixService poiScenarioAppendixService;

    @Resource
    private IAiConversationRecordService conversationRecordService;

    @Override
    public List<PoiCountToWgtResponse.SixSceneCount> selectPoiCountByKwPhone(String request) {
        log.debug("根据工号查询首页的统计信息入参{}", request);
        String telNum = JSONUtil.parseObj(request).getByPath("telNum").toString();
        if (StringUtils.isEmpty(telNum)) {
            throw new CommonException("用户工号不能为空！入参," + request);
        }
        //只查询直销人员的网格权限即可
        String table = ComConstant.TABLES.get(0);
        List<UnFollowPoiDto> list = iPoiScenarioChannelService.selectGridCodeList(null, telNum, null, table);
        if (CollectionUtils.isNotEmpty(list)) {
            UnFollowPoiDto poiDto = list.get(0);
            String gridCode = poiDto.getGridCode();
            if (StringUtils.isEmpty(gridCode)) {
                throw new CommonException("查询网格权限失败！");
            }
            PoiCountRequest poiCountRequest = new PoiCountRequest();
            poiCountRequest.setCodeStr(gridCode);
            poiCountRequest.setRoleType(RoleCodeEnum.SEVEN.getCode());
            poiCountRequest.setTelNum(telNum);
            PoiCountToWgtResponse poiCountResponse = iPoiProofreadService.selectPoiCountToWgt(poiCountRequest);
            log.debug("返回根据工号查询的首页统计信息{}", poiCountResponse.getSceneCounts());
            return poiCountResponse.getSceneCounts();
        }
        return Lists.newArrayList();
    }

    @Override
    public List<IntentionToWgtResponse> selectBusinessContent(BusinessContentRequest request) {
        log.debug("查询商机接口入参{}", request);
        List<IntentionToWgtResponse> intentionToWgtResponses = poiScenarioProofreadService.selectBusinessContent(request);
        intentionToWgtResponses.forEach(response -> {
            //其他类型的商机，将其他商机赋值给备注字段
            if (response.getIntentionType() == 5) {
                List<String> otherIntentionList = response.getOtherIntentionList();
                if (CollectionUtils.isNotEmpty(otherIntentionList)) {
                    String result = String.join(";", otherIntentionList);
                    response.setRemark(result);
                }
            }
        });
        return intentionToWgtResponses;
    }

    @Override
    public IntentionToWgtResponse selectBusinessContentDetail(BusinessDetailRequest request) {
        log.debug("商机详情接口入参{}", request);
        BusinessMarketingRequest businessMarketingRequest = new BusinessMarketingRequest();
        BeanUtils.copyProperties(request,businessMarketingRequest);
        BusinessTempResponse businessTempResponse = poiScenarioProofreadService.selectBusinessContentDetail(businessMarketingRequest);
        if (businessTempResponse == null || businessTempResponse.getIntentionInfo() == null) {
            return new IntentionToWgtResponse();
        }
        IntentionToWgtResponse response = new IntentionToWgtResponse();
        List<IntentionEntity> intentions = businessTempResponse.getIntentionInfo().getIntentions();
        if (CollectionUtils.isNotEmpty(intentions)) {
            Optional<IntentionEntity> optional = intentions.stream().filter(resp -> request.getIntentionType().equals(resp.getIntentionType())).findFirst();
            if (optional.isPresent()) {
                IntentionEntity intentionEntity = optional.get();
                BeanUtils.copyProperties(intentionEntity, response);
            }
        }
        List<String> otherIntentionList = businessTempResponse.getIntentionInfo().getOtherIntentionList();
        if (CollectionUtils.isNotEmpty(otherIntentionList)) {
            String result = String.join(";", otherIntentionList);
            response.setRemark(result);
        }
        response.setChainId(businessTempResponse.getChainId());
        response.setAddress(businessTempResponse.getAddress());
        response.setRegionCityCode(businessTempResponse.getRegionCityCode());
        response.setPoiLat(businessTempResponse.getPoiLat());
        response.setPoiLng(businessTempResponse.getPoiLng());
        response.setPoiName(businessTempResponse.getPoiName());
        response.setGridName(businessTempResponse.getGridName());
        response.setKwTime(businessTempResponse.getKwTime());
        response.setEmployeeMobile(businessTempResponse.getKwBossTel());
        response.setHandleMobile(businessTempResponse.getKdRelatedPhone());
        log.debug("网格通调用商机返回{}",response);
        return response;
    }

    @Override
    public void saveAudioRecord(AudioRequest request) {
        log.debug("网格通传入保存录音记录入参{}", request);
        poiScenarioAppendixService.saveAppendixRecord(request);
    }


    @Override
    public void updateBusinessState(BusinessMarketingRequest request) {
        log.debug("修改商机状态接口入参{}", request);
        QueryWrapper<PoiScenarioProofread> wrapper = new QueryWrapper<>();
        wrapper.lambda().select(PoiScenarioProofread::getIntentionInfo, PoiScenarioProofread::getId).eq(PoiScenarioProofread::getId, request.getChainId()).eq(PoiScenarioProofread::getKwPhone,request.getTelNum());
        PoiScenarioProofread poiScenarioProofread = poiScenarioProofreadService.getBaseMapper().selectOne(wrapper);
        if (poiScenarioProofread != null && poiScenarioProofread.getIntentionInfo() != null) {
            IntentionInfo intentionInfo = poiScenarioProofread.getIntentionInfo();
            if (intentionInfo != null) {
                List<IntentionEntity> intentions = intentionInfo.getIntentions();
                if (CollectionUtils.isNotEmpty(intentions)){
                    for (IntentionEntity intention : intentions) {
                        if (request.getIntentionType().equals(intention.getIntentionType())) {
                            intention.setMarketRemark(request.getMarketRemark());
                            intention.setMarketTime(DateTimeUtil.formatTime(new Date()));
                            intention.setSaleFlag(request.getSaleFlag());
                            break;
                        }
                    }
                }
                UpdateWrapper<PoiScenarioProofread> updateWrapper = new UpdateWrapper<>();
                updateWrapper.lambda().set(PoiScenarioProofread::getIntentionInfo, intentionInfo).eq(PoiScenarioProofread::getId, request.getChainId());
                poiScenarioProofreadService.updateIntentionInfo(JSONUtil.toJsonStr(intentionInfo), request);
            }
        }
    }

    @Override
    public void aiConversationRecordSave(AiConversationRecordRequest request) {
        log.debug("灵犀助手问答记录入参{}",request);
        AiConversationRecord aiConversationRecord = new AiConversationRecord();
        BeanUtils.copyProperties(request,aiConversationRecord);
        aiConversationRecord.setProofreadId(request.getChainId());
        int insert = conversationRecordService.getBaseMapper().insert(aiConversationRecord);
        log.debug("灵犀助手问答记录结果{}",insert);
    }
}
